package drds.plus.executor.function.scalar.filter;

import drds.plus.executor.ExecuteContext;
import drds.plus.sql_process.type.Type;
import lombok.extern.slf4j.Slf4j;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class Like extends Filter {

    Pattern pattern;
    String tarCache;

    protected Boolean computeInner(ExecuteContext executeContext, Object[] args) {
        if (args[1] == null || args[0] == null) {
            return false;
        }
        String left = Type.StringType.convert(args[0]);
        String right = Type.StringType.convert(args[1]);

        if (tarCache == null || !tarCache.equals(right)) {
            if (pattern != null) {
                throw new IllegalArgumentException("should not be here");
            }

            tarCache = right;
            // trim and remove %%

            right = right.replace("\\_", "[uANDOR]");
            right = right.replace("\\%", "[pANDOR]");
            right = right.replace("%", ".*");
            right = right.replace("_", ".");
            right = right.replace("[uANDOR]", "\\_");
            right = right.replace("[pANDOR]", "\\%");
            // case insensitive
            right = "(?i)" + right;
            right = "^" + right;
            right = right + "$";
            pattern = Pattern.compile(right);

        }
        Matcher matcher = pattern.matcher(left);
        return matcher.find();
    }

    public String[] getFunctionNames() {
        return new String[]{"like"};
    }

}
